import sql_query from '@dfeidao/atom-nodejs/db/sql-query';
import format from '@dfeidao/atom-nodejs/dt/format';
import log from '@dfeidao/atom-nodejs/logger/log';
import { IncomingHttpHeaders } from 'http';
import { spaceid, systemid } from '../../atom/config';

interface Message {
	staff_no: string;
	productid: string;
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string;
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}
interface Msg {
	msgid: string;
	send_time: string;
	msg_type_no: string;
	msg_type_name: string;
	msg_cont: string;
	msg_page_url: string;
}
export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {
	log('Service begin');
	// todo
	const sql = `select  distinct mr.msgid,m.msg_type_no,m.msg_type_name,m.msg_cont,m.send_time
	from msg_receiver mr,msg m
	where mr.is_read=0 and m.msgid=mr.msgid and mr.receiver_no='${message.staff_no}' and mr.productid='${message.productid}' ORDER BY m.send_time DESC`;

	const sql1 = `select mtp.msg_page_url
	from msg m,msg_templ_page mtp
	where mtp.msg_type_no=m.msg_type_no
	and mtp.client_type='WEB'and mtp.productid='${message.productid}'`;


	const sql2 = `select  distinct mr.msgid,m.msg_type_no,m.msg_type_name,m.msg_cont,m.send_time,mtp.msg_page_url
	from msg_receiver mr,msg m,msg_templ_page mtp
	where mr.is_read=0 and m.msgid=mr.msgid and mr.receiver_no='${message.staff_no}' and mr.productid='${message.productid}' and mtp.msg_type_no=m.msg_type_no and mtp.client_type='WEB' ORDER BY m.send_time DESC`;

	const res = await sql_query<Msg>(action_id, session_id, systemid, spaceid, sql, 'mysql');
	res.forEach((v) => {
		v.send_time = format(Number(v.send_time), 'YYYY-MM-DD HH:mm');
		v.msg_page_url = '';

	});
	const res1 = await sql_query(action_id, session_id, systemid, spaceid, sql1, 'mysql');
	const res2 = await sql_query<Msg>(action_id, session_id, systemid, spaceid, sql2, 'mysql');
	res2.forEach((v) => {
		v.send_time = format(Number(v.send_time), 'YYYY-MM-DD HH:mm');

	});

	const emp_information = await sql_query(action_id, session_id, systemid, spaceid, `select headimg from emp_information where staff_no='${message.staff_no}' and productid='${message.productid}' limit 1`, 'mysql');

	return { data: { array1: res, array2: res1, array3: res2, emp_information: emp_information[0] } };
}
